package com.billdowney.util.spring;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringUtil.applicationContext == null) {
			SpringUtil.applicationContext = applicationContext;
		}
	}

	/**
	 * 获取applicationContext
	 * 
	 * @return spring上下文
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 通过name获取 Bean
	 * 
	 * @param name 注入的bean名称
	 * @return 获取的对象
	 */
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	/**
	 * 通过class获取Bean
	 * 
	 * @param <T>
	 * @param clazz 获取的class类
	 * @return 获取到的类
	 */
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean
	 * 
	 * @param <T>
	 * @param name  注入的bean名称
	 * @param clazz 获取的class类
	 * @return 获取到的类
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

	/**
	 * 根据接口类获取所有实现的类
	 * 
	 * @param <T>
	 * @param type 获取的class类
	 * @return 获取到的类
	 */
	public static <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) {
		return getApplicationContext().getBeansOfType(type);
	}
}
